import { Button,Row,Col } from "antd";
import React, { Component, createRef } from "react";
import {regionAdd,regionRender} from '../../api/region'
let AMap = window.AMap;
var polyEditor 
var map
var polygon1  //某一个矢量图
export default class RangeMap extends Component {
  mapRef = createRef();
  state = {
    citylist: [
      { name: "重庆市", lng: 106.55, lat: 29.57 },
      { name: "上海市", lng: 121.47, lat: 31.23 },
      { name: "北京市", lng: 116.4, lat: 39.9 },
    ],
    cityIdx: 2,
  };
  componentDidMount() {
    this.initMap();
  }
  handleCity = (idx) => {
    //切换地图中心点
    this.setState({ cityIdx: idx }, () => {
      this.initMap();
    });
  };

  initMap = () => {
    //初始化地图
    let { cityIdx, citylist } = this.state;
    let { lng, lat } = citylist[cityIdx];
    // if(map){map.destory()}  //先销毁已有地图
    map = new AMap.Map(this.mapRef.current, {
      zoom: 10, //缩放级别
      center: [lng, lat],
    });

    // 方法1:静态固定路径渲染矢量图
    // var path2 = [
    //   [116.474595, 40.001321],
    //   [116.473526, 39.999865],
    //   [116.476284, 40.000917],
    // ];
    // var polygon2 = new AMap.Polygon({
    //   path: path2,
    // });

    // map.add([polygon2]);  //将绘制的形状添加到地图中
    // // map.setFitView();
    // polyEditor = new AMap.PolygonEditor(map);  //在地图上创建可编辑的矢量图区域
    // polyEditor.addAdsorbPolygons([polygon2]);

    // 方法2:动态从后端加载对应城市的矢量图
    regionRender(citylist[cityIdx].name).then(res=>{
      console.log(res);
      this.renderPolygon(res.data.results[0])
    })
    // polyEditor.on("add", function (data) {
    //   console.log(data);
    //   var polygon = data.target;
    //   polyEditor.addAdsorbPolygons(polygon);
    //   polygon.on("dblclick", () => {
    //     polyEditor.setTarget(polygon);
    //     polyEditor.open();
    //   });
    // });
    // polygon1.on("dblclick", () => {
    //   polyEditor.setTarget(polygon1);
    //   polyEditor.open();
    // });
    // polygon2.on("dblclick", () => {
    //   polyEditor.setTarget(polygon2);
    //   polyEditor.open();
    // });
    
    // polyEditor.setTarget(polygon2);
    // polyEditor.open();
  };

  renderPolygon = (polyData)=>{  //渲染矢量图逻辑
    // polyData['path0']
    let polyArr = []
    for(let attr in polyData){
      if(attr.indexOf('path')!=-1){
        let poly = new AMap.Polygon({ //根据数据包生成矢量图对象
            path: polyData[attr],
        })
        poly.on("dblclick", () => { //为矢量图对象添加事件
          polyEditor.setTarget(poly);
          polyEditor.open();
        });
        polyArr.push(poly)
      }
    }
    map.add(polyArr);  //将绘制的形状添加到地图中
    // // map.setFitView();
    polyEditor = new AMap.PolygonEditor(map);  //在地图上创建可编辑的矢量图区域
    polyEditor.addAdsorbPolygons(polyArr); //初始化显示矢量图
    polyEditor.on("add", function (data) {
      console.log('新增的矢量图信息',data);
      var polygon = data.target;
      polygon1 = polygon   //保存提交时，可以获取矢量图数据
      polyEditor.addAdsorbPolygons(polygon); //新增矢量图
      polygon.on("dblclick", () => {
        polyEditor.setTarget(polygon);
        polyEditor.open();
      });
    }); 
    
  }

  createPolygon = ()=>{  //新增矢量图
    polyEditor.close();
    polyEditor.setTarget();
    polyEditor.open();
  }

  handlePolygonDone = ()=>{ //完成编辑
    polyEditor.close()
    if(!polygon1){return}
    let paths = polygon1.getPath()  //获取新增的矢量图的形状数据数组
    console.log(paths);
    let arr = paths.map(item=>{ //处理数据包格式
      return [item.lng,item.lat]
    })
    console.log(arr);
    let {cityIdx,citylist} = this.state
    regionAdd({ 
      ...citylist[cityIdx],
      path0:arr
    })
  }

  render() {
    let { cityIdx, citylist } = this.state;
    return (
      <>
        <Row justify="space-between">
          <Col>
          {citylist.map((item, index) => {
          return (
            <Button
              type="primary"
              ghost={index != cityIdx}
              onClick={() => {
                this.handleCity(index);
              }}
              key={index}
            >
              {item.name}
            </Button>
          );
        })}
          </Col>
          <Col>
            <Button type="primary" onClick={this.createPolygon}>新增范围</Button>
            <Button type="primary" onClick={this.handlePolygonDone}>提交保存</Button>
          </Col>
        </Row>
        <div ref={this.mapRef} style={{ height: "600px" }}>
          RangeMap
        </div>
      </>
    );
  }
}
